﻿using System.Data;
using System.Reflection;

namespace Singer.Core.DataExtensions;

public static class ListExtensions
{
    public static DataTable ToDataTable<T>(this List<T> list, string tableName = "") where T : class
    {
        DataTable dt = new DataTable();
        Type type = typeof(T);
        dt.TableName = string.IsNullOrWhiteSpace(tableName) ? type.Name : tableName;
        foreach (PropertyInfo property in type.GetProperties())
        {
            dt.Columns.Add(property.Name, property.PropertyType);
        }
        foreach (var item in list)
        {
            DataRow dr = dt.NewRow();
            foreach (PropertyInfo property in type.GetProperties())
            {
                dr[property.Name] = property.GetValue(item);
            }
            dt.Rows.Add(dr);
        }
        return dt;
    }
}
